#!/bin/sh

#
# Test upgrading an xdelta3-encoded update by streaming it
#
# While this should be identical to test 172, it exercises differences in
# how zip files get processed when they're streamed vs. not streamed. When
# streamed, they no longer can fall back to the ZIP central directory (at
# the end of the file)
#

. "$(cd "$(dirname "$0")" && pwd)/common.sh"

FWFILE2="$WORK/fwup2.fw"

cat >"$CONFIG" <<EOF
define(ROOTFS_A_PART_OFFSET, 1024)
define(ROOTFS_A_PART_COUNT, 1024)
define(ROOTFS_B_PART_OFFSET, 2048)
define(ROOTFS_B_PART_COUNT, 1024)

file-resource rootfs.original {
        host-path = "${TESTFILE_1K}"
}
file-resource rootfs.next {
        host-path = "${TESTFILE_1K}"
}

task complete {
    on-init { raw_memset(\${ROOTFS_B_PART_OFFSET}, \${ROOTFS_B_PART_COUNT}, 0) }
    on-resource rootfs.original { raw_write(\${ROOTFS_A_PART_OFFSET}) }
}
task upgrade {
    on-resource rootfs.next {
        delta-source-raw-offset=\${ROOTFS_A_PART_OFFSET}
        delta-source-raw-count=\${ROOTFS_A_PART_COUNT}
        raw_write(\${ROOTFS_B_PART_OFFSET})
    }
}
EOF

# Create the firmware file, then "burn it"
$FWUP_CREATE -c -f "$CONFIG" -o "$FWFILE"
$FWUP_APPLY -a -d "$IMGFILE" -i "$FWFILE" -t complete

# Check that the resources got copied to all of the right places
cmp_bytes 1024 "$TESTFILE_1K" "$IMGFILE" 0 524288

# Manually create the delta upgrade by replacing rootfs.next
# with the delta3 version
mkdir -p "$WORK/data"
xdelta3 -A -S -f -s "$TESTFILE_1K" "$TESTFILE_1K" "$WORK/data/rootfs.next"
cp "$FWFILE" "$FWFILE2"
(cd "$WORK" && zip "$FWFILE2" data/rootfs.next)

# NOTE: use "unzip -v $FWFILE2" to verify archive contents

# Now upgrade the IMGFILE file by streaming it
cat "$FWFILE2" | $FWUP_APPLY -a -d "$IMGFILE" -i - -t upgrade

cmp_bytes 1024 "$TESTFILE_1K" "$IMGFILE" 0 524288  # Same
cmp_bytes 1024 "$TESTFILE_1K" "$IMGFILE" 0 1048576 # Updated

# Check that the firmware metadata didn't change (including the UUID)
$FWUP_APPLY_NO_CHECK -m -i "$FWFILE" > "$WORK/original.metadata"
$FWUP_APPLY_NO_CHECK -m -i "$FWFILE2" > "$WORK/delta_update.metadata"
diff "$WORK/original.metadata" "$WORK/delta_update.metadata"

# Check that the verify logic works on both files
$FWUP_VERIFY -V -i "$FWFILE"
$FWUP_VERIFY -V -i "$FWFILE2"
